package com.rivercloud.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.FieldMeta;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import com.rivercloud.dao.ExcelDAO;
import com.rivercloud.dao.TableColDao;
import com.rivercloud.dao.TableDao;
import com.rivercloud.dao.TableRowDao;
import com.rivercloud.dao.UserDao;
import com.rivercloud.dao.UserProjectDao;
import com.rivercloud.dao.Impl.TableColDaoImpl;
import com.rivercloud.dao.Impl.TableDaoImpl;
import com.rivercloud.dao.Impl.TableRowDaoImpl;
import com.rivercloud.dao.Impl.UserDaoImpl;
import com.rivercloud.dao.Impl.UserProjectDaoImpl;
import com.rivercloud.entity.ExcelTable;
import com.rivercloud.entity.TableCol;
import com.rivercloud.entity.TableRow;
import com.rivercloud.entity.User;
import com.rivercloud.entity.UserTable;
import com.rivercloud.filter.LoginFilter;

/**
 * Created by lq on 2016/11/29/0029.
 */
@Filters(@By(type=LoginFilter.class, args={"user", "/login.jsp"}))  
@At("/excel")
@Fail("http:500")
public class TableController {

	@Inject
	private ExcelDAO excelDAO = new ExcelDAO();
	private TableColDao tableColDao = new TableColDaoImpl();
	private TableRowDao tableRowDao = new TableRowDaoImpl();
	private UserProjectDao userProjectDao = new UserProjectDaoImpl();
	private TableDao tableDao = new TableDaoImpl();
	private UserDao userDao = new UserDaoImpl();
	

	@At("/upload")
	@Ok("redirect:/templates.jsp")
	@AdaptBy(type = UploadAdaptor.class, args = {})
	public void uploadExcel(HttpServletRequest request, HttpServletResponse response, @Param("file") TempFile tempFile)
			throws ServletException, IOException {
		File file = tempFile.getFile(); // 保存的临时文件
		FieldMeta meta = tempFile.getMeta(); // 原本的文件信息
		String filename = meta.getFileLocalName(); // 文件名称
		excelDAO.insert(filename, file);
	}

	@At("/download")
	@Ok("redirect:/download.jsp")
	public void downloadExcel(HttpServletResponse response, HttpServletRequest request) throws IOException {
		String filename = request.getParameter("filename");
		Map<Integer, Object[]> map = excelDAO.find(filename);
		HSSFWorkbook workbook = new HSSFWorkbook();
		Sheet sheet = workbook.createSheet("sheet1");
		for (int i = 0; i < map.size(); i++) {
			String[] value = new String[map.get(0).length];
			for (int j = 0; j < map.get(0).length; j++) {
				value[j] = map.get(i)[j].toString();
			}
			Row row = workbook.getSheet("sheet1").createRow(i);// 创建第一行
			for (int k = 0; k < value.length; k++) {
				Cell cell = row.createCell(k);
				cell.setCellValue(value[k].trim());
			}
		}
		FileOutputStream out = new FileOutputStream("D:/" + filename);
		workbook.write(out);
		out.close();
	}

	// 可编辑列表
	@At("/list")
	@Ok("jsp:jsp.list")

	@Fail("jsp:jsp.500")
	public void listExcel(HttpServletRequest request) {
		Object[] fileNames = excelDAO.getCollectionNames();
		request.setAttribute("fileNames", fileNames);
	}

	

	// 只读的列表
	@At("/scan")
	@Fail("jsp:jsp.500")
	@Ok("jsp:jsp.lists")
	public void listExcels(HttpServletRequest request) {
		Object[] fileNames = excelDAO.getCollectionNames();
		request.setAttribute("fileNames", fileNames);
	}

	// 可编辑的展示
	@At("/show")
	@Ok("json")
	public Map readExcel(HttpServletRequest request) {
		String filename = request.getParameter("filename");
		Map<Integer, Object[]> map = excelDAO.find(filename);
		return map;
	}
	
	@At("/look")
	@Ok("jsp:jsp.editTable")
	public void lookExcels(HttpServletRequest request) {
		try {
			String filename = request.getParameter("filename");
			Map<Integer, Object[]> map = excelDAO.find(filename);
			
			 for (Integer key : map.keySet()) {
				 Object[] obj = map.get(key);
				  System.out.println(key + "     " + obj.toString());
				  }
			
			Object[] title = map.get(0);// 得到Excel的列标题
			
			List data = new ArrayList();// 得到Excel的内容
			for (int i = 1; i < map.size(); i++) {
				Object[] obj = map.get(i);
				
				data.add(obj);
			}
			
			request.setAttribute("filename", filename);
			request.setAttribute("title", title);
			request.setAttribute("data", data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@At("/edit")
	@Ok("jsp:jsp.table")
	public void readExcel2(HttpServletRequest request) {
		String filename = request.getParameter("filename");
		Map<Integer, Object[]> map = excelDAO.find(filename);
		Object[] title = map.get(0);// 得到Excel的列标题
		List data = new ArrayList();// 得到Excel的内容
		for (int i = 0; i < map.size(); i++) {
			Object[] obj = map.get(i + 1);
			data.add(obj);
		}
		request.setAttribute("title", title);
		request.setAttribute("data", data);
	}
	
	@At("/editTable")
	@Ok("jsp:jsp.editTable")
	public void editTable(HttpServletRequest request) {
		try {
			String tableName = request.getParameter("tableName");
			int tableId = Integer.parseInt(request.getParameter("tableId"));
			int userId = Integer.parseInt(request.getParameter("userId"));
			String filename = tableName + ".xls";
			ExcelTable table = tableDao.findTableById(tableId);
			Map<Integer, Object[]> map = excelDAO.find(filename);
			
			 for (Integer key : map.keySet()) {
				 Object[] obj = map.get(key);
				  System.out.println(key + "  ---   " + obj.toString());
				  }
			
			Object[] title = map.get(0);// 得到Excel的列标题
			
			List data = new ArrayList();// 得到Excel的内容
			for (int i = 1; i < map.size(); i++) {
				Object[] obj = map.get(i);
				
				data.add(obj);
			}
//			int tableId = tableDao.findIdByTableName(tableName);
			
			List<Integer> colNumList = tableColDao.findColNumByTableId(tableId);
			List<TableCol> tableColList = tableColDao.findByTableId(tableId);
			List<TableRow> tableRowList = tableRowDao.findRowsByTableId(tableId);
			UserTable existUserTable = new UserController().checkCollection(userId,tableId);
			String  projectIdS = request.getParameter("projectId");
			System.out.println(projectIdS);
			if(projectIdS != "" && projectIdS != null && !projectIdS.equals("") ){
				int projectId = Integer.parseInt(projectIdS);
				List<Integer> userIds = userProjectDao.findUserIdsByProjectId(projectId);
				List<User> users = userDao.findUserByIds(userIds);
				request.setAttribute("users", users);
			}
			
			
			request.setAttribute("existUserTable", existUserTable);
			request.setAttribute("tableName", tableName);
			request.setAttribute("table", table);
			request.setAttribute("title", title);
			request.setAttribute("data", data);
			request.setAttribute("colNumList", colNumList);
			request.setAttribute("tableColList", tableColList);
			request.setAttribute("tableRowList", tableRowList);
			request.setAttribute("tableId", tableId);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 只读的展示
	@At("/read")
	@Ok("jsp:jsp.show")
	public void readExcels(HttpServletRequest request) {
		try {
			String filename = request.getParameter("filename");
			Map<Integer, Object[]> map = excelDAO.find(filename);
			Object[] title = map.get(0);// 得到Excel的列标题
			List data = new ArrayList();// 得到Excel的内容
			for (int i = 0; i < map.size(); i++) {
				Object[] obj = map.get(i + 1);
				
				data.add(obj);
			}
			System.out.println(title.toString());
			System.out.println(data.toString());
			request.setAttribute("title", title);
			request.setAttribute("data", data);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	

	// 更新excel到数据库中
	@At("/write")
	public void writeExcel(HttpServletRequest request) {
		System.out.println("------");
		String json = request.getParameter("json");
		String filename = request.getParameter("filename");
		NutMap map = Json.fromJson(NutMap.class, json);
		Map<Integer, String[]> data = new HashMap();
		for (Map.Entry entry : map.entrySet()) {
			String str = entry.getValue().toString();
			String str1 = str.substring(1, str.indexOf("]"));
			String[] value = str1.split(",");
			System.out.println(entry.getKey().getClass());
			System.out.println(Integer.parseInt(entry.getKey().toString()));
			int i = Integer.parseInt(entry.getKey().toString());
			data.put(i, value);
		}
		excelDAO.updata(data, filename);
	}
	
	// 保存表格到数据库
		@At("/save")
		public void saveExcel(HttpServletRequest request) {
			
			String json = request.getParameter("json");
			System.out.println(json);
			String tableName = request.getParameter("tableName");
			String filename = tableName + ".xls";
			System.out.println(filename);
			NutMap map = Json.fromJson(NutMap.class, json);
			System.out.println(map);
			Map<Integer, String[]> data = new HashMap();
			for (Map.Entry entry : map.entrySet()) {
				String str = entry.getValue().toString();
				String str1 = str.substring(1, str.indexOf("]"));
				String[] value = str1.split(",");
				System.out.println(entry.getKey().getClass());
				System.out.println(Integer.parseInt(entry.getKey().toString()));
				int i = Integer.parseInt(entry.getKey().toString());
				data.put(i, value);
			}
			excelDAO.saveExcel(data, filename);
		}

	// 删除excel
	@At("/delete")
	@Ok("json")
	public Map deleteExcel(HttpServletRequest request) {
		String filename = request.getParameter("filename");
		Map map = new HashMap();
		excelDAO.delete(filename);
		map.put("true", true);
		return map;
	}
}
